/**
 * 历史对话
 */
import React, { useState, useEffect, useCallback } from "react";  // 添加 useEffect
import classNames from "classnames";
import dayjs from "dayjs";
import { useGlobalContext } from "../../context/GlobalContext";  // 添加这行
import { getApiUrl } from "../../config/api";
import IconChat from "../../assets/chat.svg";
import IconDelete from "../../assets/delete.svg";
import IconEdit from "../../assets/edit.svg";
import "./index.css";

const HistoryChats = () => {
  const [activeChatId, setActiveChatId] = useState("");
  const [conversations, setConversations] = useState([]);
  const [showSearch, setShowSearch] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState("");
  const [originalConversations, setOriginalConversations] = useState([]);
  const { setChatContent } = useGlobalContext();

  // 使用 useCallback 包装的 toggleSearch
  const toggleSearch = useCallback(() => {
    setShowSearch(prev => !prev);
    if (!showSearch) {  // 添加这个条件判断
      setSearchKeyword("");
      setConversations(originalConversations);
    }
  }, [originalConversations, showSearch]);

  // Add initialization useEffect
  useEffect(() => {
    fetchHistory();
  }, []);

  // Search event listener useEffect
  useEffect(() => {
    const handleToggleSearch = () => {
      toggleSearch();
    };

    window.addEventListener('toggleSearch', handleToggleSearch);
    return () => {
      window.removeEventListener('toggleSearch', handleToggleSearch);
    };
  }, [toggleSearch]);

  // 获取历史记录
  // 修改 fetchHistory 函数
  const fetchHistory = async () => {
    try {
      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');
      
      const response = await fetch(getApiUrl('/api/chat/history'), {
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
          'Content-Type': 'application/json'
        }
      });
      const data = await response.json();
      if (data.ok) {
        const formattedData = [{
          title: "历史对话",
          chats: data.data.map(item => ({
            chat_id: item.id,
            chat_title: item.question.substring(0, 50) + (item.question.length > 50 ? '...' : ''), // 使用问题作为标题，并限制长度
            created_at: dayjs(item.created_at).format('YYYY-MM-DD HH:mm:ss'),
          }))
        }];
        setConversations(formattedData);
        setOriginalConversations(formattedData);
      }
    } catch (error) {
      console.error("获取历史记录失败:", error);
    }
  };

  // 添加搜索处理函数
  const handleSearch = (keyword) => {
    setSearchKeyword(keyword);
    if (!keyword.trim()) {
      setConversations(originalConversations);
      return;
    }

    const filteredData = originalConversations.map(group => ({
      ...group,
      chats: group.chats.filter(chat => 
        chat.chat_title.toLowerCase().includes(keyword.toLowerCase())
      )
    }));
    setConversations(filteredData);
  };

  const handleClearAll = async () => {
    try {
      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');
      
      // 修改为正确的路由
      const response = await fetch(getApiUrl('/api/chat/clear-all'), {  
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
          'Content-Type': 'application/json'
        }
      });
  
      const data = await response.json();
      if (data.ok) {
        setConversations([{  // 修改为正确的初始状态
          title: "历史对话",
          chats: []
        }]);
        setOriginalConversations([{
          title: "历史对话",
          chats: []
        }]);
        setChatContent([]);
      }
    } catch (error) {
      console.error("清除所有对话失败:", error);
    }
  };

  // 添加点击对话的函数
  const handleChatClick = async (chat) => {
    if (!chat?.chat_id) return;
    
    setActiveChatId(chat.chat_id);
    
    try {
      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');
      
      const response = await fetch(getApiUrl(`/api/chat/detail/${chat.chat_id}`), {
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
          'Content-Type': 'application/json'
        }
      });
      
      const data = await response.json();
      if (data.ok) {
        const chatContent = [
          { role: 'user', content: data.data.question },
          { role: 'assistant', content: data.data.answer }
        ];
        setChatContent(chatContent);
      }
    } catch (error) {
      console.error("获取对话详情失败:", error);
    }
  };

  // 添加删除对话的函数
  const handleDelete = async (chatId, e) => {
    e.stopPropagation();
    try {
      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');
      
      const response = await fetch(getApiUrl(`/api/chat/delete/${chatId}`), {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
          'Content-Type': 'application/json'
        }
      });

      const data = await response.json();
      if (data.ok) {
        fetchHistory();
      }
    } catch (error) {
      console.error("删除对话失败:", error);
    }
  };

  // 添加编辑对话的函数
  const handleEdit = async (chatId, e) => {
    e.stopPropagation();
    
    try {
      const token = localStorage.getItem('token');
      const cleanToken = token.replace(/['"]+/g, '');
      
      // 1. 获取对话详情
      const detailResponse = await fetch(getApiUrl(`/api/chat/detail/${chatId}`), {
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
          'Content-Type': 'application/json'
        }
      });
      
      const detailData = await detailResponse.json();
      if (!detailData.ok) {
        throw new Error("获取对话详情失败");
      }

      // 2. 获取用户输入
      const newContent = prompt("请输入新的内容:", detailData.data.question);
      if (!newContent || newContent === detailData.data.question) return;

      // 3. 发送更新请求，使用两个模型的回答作为提示
      const updateResponse = await fetch(getApiUrl(`/api/chat/update/${chatId}`), {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${cleanToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ 
          content: newContent,
          useModels: ['doubao', 'deepseek'] // 使用两个模型的回答作为提示
        })
      });

      const updateData = await updateResponse.json();
      if (updateData.ok) {
        // 4. 更新界面显示
        setChatContent([
          { role: 'user', content: newContent },
          { role: 'assistant', content: updateData.data }
        ]);
        fetchHistory();
      }
    } catch (error) {
      console.error("修改对话失败:", error);
    }
  };

  // 修改 useEffect，添加新建对话事件监听
  useEffect(() => {
    const handleNewChat = () => {
      // 清空当前选中状态
      setActiveChatId("");
    };

    window.addEventListener('refreshHistory', handleNewChat);
    return () => {
      window.removeEventListener('refreshHistory', handleNewChat);
    };
  }, []);

  // 添加刷新历史记录的事件监听
  useEffect(() => {
    const handleRefreshHistory = () => {
      fetchHistory();
    };
  
    window.addEventListener('refreshHistory', handleRefreshHistory);
    return () => {
      window.removeEventListener('refreshHistory', handleRefreshHistory);
    };
  }, []);

  return (
    <div className="history-chats">
      {/* 添加搜索框 */}
      {showSearch && (
        <div className="history-chats__search">
          <input
            type="text"
            placeholder="搜索历史对话..."
            value={searchKeyword}
            onChange={(e) => handleSearch(e.target.value)}
            autoFocus
          />
        </div>
      )}
      {conversations?.map((item, index) => (
        <div key={`conversation-${index}`} className="history-charts__group">
          <div className="history-chats__title">
            <span>{item.title}</span>
            <button className="history-chats__clear" onClick={handleClearAll}>
              清除对话
            </button>
          </div>
          <div className="history-chats__content">
            {item.chats?.map((chat, index) => (
              <div
                key={`${item.title}-chat-${index}`}
                className={classNames("history-chats__content__item", {
                  "history-chats__content__item-active": activeChatId === chat?.chat_id,
                })}
                onClick={() => handleChatClick(chat)}
              >
                <img src={IconChat} alt="聊天" />
                <div className="history-chats__content__item-info">
                  <p className="chat-title">{chat.chat_title}</p>
                  <p className="chat-time">{chat.created_at}</p>
                </div>
                <div className="history-chats__content__item-right">
                  <button onClick={(e) => handleDelete(chat.chat_id, e)}>
                    <img src={IconDelete} alt="删除" />
                  </button>
                  <div className="concave-right-angled-triangle"></div>
                  <button onClick={(e) => handleEdit(chat.chat_id, e)}>
                    <img src={IconEdit} alt="修改" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};

export { HistoryChats };
